package com.park.controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.park.model.Alipayrecord;
import com.park.model.Constants;
import com.park.model.MicropayStopcarInfoEntity;
import com.park.model.PosChargeData;
import com.park.service.AliParkFeeService;
import com.park.service.AlipayrecordService;
import com.park.service.HongxingService;
import com.park.service.JedisClient;
import com.park.service.ParkToAliparkService;
import com.park.service.PosChargeDataService;
import com.park.service.Utility;
import com.thoughtworks.xstream.alias.ClassMapper.Null;
import com.util.CCBUtil;
import com.util.OkHttpUtils;

@Controller
@RequestMapping("weipay")
public class WeiPayController {
	
	@Autowired
	HongxingService hongxingService;
	@Autowired
	PosChargeDataService poschargedataService;
	@Autowired
	ParkToAliparkService parkToAliparkService;
	@Autowired
	AliParkFeeService parkFeeService;
	@Autowired
	AlipayrecordService alipayrecordService;
	@Resource(name = "jedisClient")
	private JedisClient jedisClient;
	
	private static Log logger = LogFactory.getLog(WeiPayController.class);
	@RequestMapping(value = "commonNotifyPay", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String commonNotifyPay(@RequestBody Map<String, Object> args) throws ParseException{
		logger.info("commonNotifyPay:"+args.toString());
		int poschargeId=(int) args.get("poschargeId");
		String paidAmount=(String) args.get("paidAmount");	
		String chargeAmount=args.get("chargeAmount")!=null?(String) args.get("chargeAmount"):null;	
		String tradeNo=(String) args.get("tradeNo");
		String plateNumber=(String) args.get("plateNumber");
		int payType=args.get("payType")!=null?(int)args.get("payType"):1;
		String operator=args.get("operator")!=null?(String) args.get("operator"):null;
		Map<String, Object> ret = new HashMap<String, Object>();
		//更新poschargeData的状态
		PosChargeData lastCharge =poschargedataService.getById(poschargeId);
		if (!lastCharge.getCardNumber().equals(plateNumber)) {
			ret.put("status", 1002);
			ret.put("message", "plateNumber error");
			logger.info(args.get("plateNumber")+"与数据库中存有的车牌号不一致--"+lastCharge.getCardNumber());
			return Utility.gson.toJson(ret);
		}
		logger.info("获取到charge记录 "+lastCharge.getCardNumber()+" id:"+lastCharge.getId());
		lastCharge.setPaidMoney(Double.parseDouble(paidAmount));
		
		if (StringUtils.isNotEmpty(chargeAmount)) {
			lastCharge.setChargeMoney(Double.parseDouble(chargeAmount));
		}
		else {
			lastCharge.setChargeMoney(Double.parseDouble(paidAmount));
		}
	//	lastCharge.setChargeMoney(Double.parseDouble(paidAmount));
		lastCharge.setPaidCompleted(true);
		lastCharge.setPayType(payType);
		lastCharge.setPayTime(new SimpleDateFormat(Constants.DATEFORMAT).format(new Date()));
		
		if (operator!=null) {
			lastCharge.setOperatorId(operator);
		}
		lastCharge.setRejectReason(lastCharge.getRejectReason()+" | 场内支付时间:"+new SimpleDateFormat(Constants.DATEFORMAT).format(new Date()));
		lastCharge.setPayTime(new SimpleDateFormat(Constants.DATEFORMAT).format(new Date()));
		lastCharge.setOther(10.0);
		poschargedataService.update(lastCharge);
		jedisClient.set("mobilepay"+lastCharge.getParkId()+lastCharge.getCardNumber(), String.valueOf(lastCharge.getId()), 60*60*5);
		logger.info(lastCharge.getCardNumber()+" 移动支付记录已更新");
		//清场重复入场的
		try {
			//避免主从不一致带来的影响
//			Thread.sleep(100);
//			List<PosChargeData> posChargeDatas=poschargedataService.getDebt(lastCharge.getCardNumber());
//			for (PosChargeData posChargeData : posChargeDatas) {
//				if (posChargeData.getParkId()==lastCharge.getParkId()) {
//					posChargeData.setPaidCompleted(true);
//					posChargeData.setPaidMoney(0);
//					posChargeData.setChargeMoney(0);
//					posChargeData.setUnPaidMoney(0);
//					posChargeData.setExitDate1(new Date());
//					posChargeData.setRejectReason("微信支付清场");
//					logger.info(posChargeData.getCardNumber()+"清场"+posChargeData.getId());
//				//	poschargedataService.update(posChargeData);
//					poschargedataService.deleteById(posChargeData.getId());
//				}
//			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//支付宝记录的添加  微信暂时添加进来
		Alipayrecord alipayrecord=new Alipayrecord();
		alipayrecord.setStatus("5");
		alipayrecord.setMoney(Double.parseDouble(paidAmount));
		alipayrecord.setAlitradeno(tradeNo);
		alipayrecord.setPoschargeid(poschargeId);
		alipayrecord.setDate(new Date());
		int num=alipayrecordService.insertSelective(alipayrecord);
		
		if (num==1) {
			ret.put("status", 1001);
			ret.put("message", "success");
		}
		else {
			ret.put("status", 1002);
			ret.put("message", "failed");
		}
		logger.info(ret.toString());
		return Utility.gson.toJson(ret);
	}
	
	
	@RequestMapping(value = "notifyPay", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String notifyUrlWebPay(@RequestBody Map<String, Object> args){
		logger.info("notifyPay:"+args.toString());
		int poschargeId=(int) args.get("poschargeId");
		String paidAmount=(String) args.get("paidAmount");	
		String tradeNo=(String) args.get("tradeNo");
		
		Map<String, Object> ret = new HashMap<String, Object>();
		//更新poschargeData的状态
		PosChargeData lastCharge =poschargedataService.getById(poschargeId);
	
		
		lastCharge.setPaidMoney(Double.parseDouble(paidAmount));
		lastCharge.setChargeMoney(Double.parseDouble(paidAmount));
		lastCharge.setPaidCompleted(true);
		lastCharge.setPayType(1);
	
		lastCharge.setRejectReason("weipay"+new SimpleDateFormat(Constants.DATEFORMAT).format(new Date()));
		lastCharge.setOther(10.0);
		poschargedataService.update(lastCharge);
		jedisClient.set(lastCharge.getId()+"-mobilepay", Utility.formatDatetime(new Date()),60*60*24*3);
	//	jedisClient.set(lastCharge.getCardNumber()+"-"+lastCharge.getParkId()+"-mobilepay",String.valueOf(lastCharge.getId()),60*60*12);
		try {
			//避免主从不一致带来的影响
			Thread.sleep(100);
			List<PosChargeData> posChargeDatas=poschargedataService.getDebt(lastCharge.getCardNumber());
			for (PosChargeData posChargeData : posChargeDatas) {
				if (posChargeData.getParkId()==lastCharge.getParkId()) {
					posChargeData.setPaidCompleted(true);
					posChargeData.setPaidMoney(0);
					posChargeData.setChargeMoney(0);
					posChargeData.setUnPaidMoney(0);
					posChargeData.setRejectReason("微信支付清场");
				
					posChargeData.setPayType(1);
				//	poschargedataService.update(posChargeData);
					
					poschargedataService.deleteById(posChargeData.getId());
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//支付宝记录的添加  微信暂时添加进来
		Alipayrecord alipayrecord=new Alipayrecord();
		alipayrecord.setStatus("5");
		alipayrecord.setMoney(Double.parseDouble(paidAmount));
		alipayrecord.setAlitradeno(tradeNo);
		alipayrecord.setPoschargeid(poschargeId);
		alipayrecord.setDate(new Date());
		int num=alipayrecordService.insertSelective(alipayrecord);
		
		if (num==1) {
			ret.put("status", 1001);
			ret.put("message", "success");
		}
		else {
			ret.put("status", 1002);
			ret.put("message", "failed");
		}
		logger.info("notifyPay:"+ret.toString());
		return Utility.gson.toJson(ret);
	}
	
	@RequestMapping(value = "notifyPayWithExitTime", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String updateExitTime(@RequestBody Map<String, Object> args){
		logger.info("notifyPayWithExitTime:"+args.toString());
		int poschargeId=(int) args.get("poschargeId");
		String paidAmount=(String) args.get("paidAmount");	
		String tradeNo=(String) args.get("tradeNo");	
		//更新poschargeData的状态
		PosChargeData lastCharge =poschargedataService.getById(poschargeId);
		lastCharge.setChargeMoney(Double.parseDouble(paidAmount));
		lastCharge.setPaidCompleted(true);
		lastCharge.setPayType(1);
		lastCharge.setExitDate1(new Date());
		lastCharge.setRejectReason("weipay"+new SimpleDateFormat(Constants.DATEFORMAT).format(new Date()));
		poschargedataService.update(lastCharge);
	//	jedisClient.set(lastCharge.getCardNumber()+"-"+lastCharge.getParkId()+"-mobilepay",String.valueOf(lastCharge.getId()),60*60*12);
		jedisClient.set(lastCharge.getId()+"-mobilepay", Utility.formatDatetime(new Date()),60*60*24*3);
		//支付宝记录的添加  微信暂时添加进来
		Alipayrecord alipayrecord=new Alipayrecord();
		alipayrecord.setStatus("5");
		alipayrecord.setMoney(Double.parseDouble(paidAmount));
		alipayrecord.setAlitradeno(tradeNo);
		alipayrecord.setPoschargeid(poschargeId);
		alipayrecord.setDate(new Date());
		int num=alipayrecordService.insertSelective(alipayrecord);
		Map<String, Object> ret = new HashMap<String, Object>();
		if (num==1) {
			ret.put("status", 1001);
			ret.put("message", "success");
		}
		else {
			ret.put("status", 1002);
			ret.put("message", "failed");
		}
		logger.info("notifyPayWithExitTime:"+args.toString());
		return Utility.gson.toJson(ret);
	}
	
	@RequestMapping(value = "micropay", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public Map<String,Object> micropay(
			@RequestBody MicropayStopcarInfoEntity msiEntity,
			HttpServletRequest request){
		logger.info("[micropay]参数:"+msiEntity);
		Map<String,Object> result = new HashMap<String, Object>();
		PosChargeData posChargeData = poschargedataService.getById(msiEntity.getId());
		DecimalFormat df = new DecimalFormat("#.00");
		CCBUtil ccb = new CCBUtil();
		boolean bool = ccb.payBeSwept(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()), posChargeData.getCardNumber(), df.format(posChargeData.getChargeMoney()),msiEntity.getAuth_code());
		System.out.println("bool:"+bool);
		if(bool) {
			String weixinUrl = "http://weixin.iotclouddashboard.com/operatingDevice/open";
			JSONObject jsonA = new JSONObject();
			jsonA.put("operatorId", "建行回调");
			jsonA.put("poschargeId", posChargeData.getId());
			jsonA.put("mac", msiEntity.getMac());
			jsonA.put("time", new SimpleDateFormat("yyyyMMddHHmmssSS").format(posChargeData.getEntranceDate()));
			jsonA.put("plateNumber", posChargeData.getCardNumber());
			System.out.println(jsonA);
			String resultq1 = null;
			try {
				resultq1 = OkHttpUtils.getInstance().postJsonNoToken(
						weixinUrl,
						jsonA.toString());
		}catch (IOException e1) {
			result.put("message", "失败");
			return result;
		}
			if(!StringUtils.isEmpty(resultq1)) {
				result.put("message", "成功");
			}else {
				result.put("message", "失败");
			}
		return result;
	}
		result.put("message", "失败");
		return result;
	}
}
